package com.rech.xbexpress3;

import com.rech.dialog.CustomDialog;
import com.rech.utils.LogUtil;
import com.rech.utils.OtherUtil;
import com.rech.view.NumberKeyboardView;
import com.rech.xbexpress3.R;
import com.yzq.zxinglibrary.android.CaptureActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.WindowManager;
import android.widget.ImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Kd3Activity extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;
    private long mLastClickTime = 0;
    public static final long TIME_INTERVAL = 3000L;
    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar


        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    private EditText kd3_ljm;
    private NumberKeyboardView keyboardView;
    private LinearLayout ll_take;
    private ImageView iv_delete;
    private TextView djs ;
    private Timer countTimer;
    private int jjcount = 100;
    private int jjcount2 = 5;
    private Timer countTimer2;
    private CustomDialog commitDialog;
    private TextView dialog_djs;
    private TextView tv_hint;
    private Button btn_confirm;

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setContentView(R.layout.activity_kd3);

        kd3_ljm = (EditText) findViewById(R.id.kd3_ljm);
        djs = findViewById(R.id.tv_djs);
        ll_take = (LinearLayout) findViewById(R.id.ll_take);
        keyboardView = new NumberKeyboardView(this, false);
        ll_take.addView(keyboardView);
        //keyboardView = (NumberKeyboardView) findViewById(R.id.keyboardView);
        final Button tv_one = keyboardView.findViewById(R.id.one);
        final Button tv_two = keyboardView.findViewById(R.id.two);
        final Button tv_three = keyboardView.findViewById(R.id.three);
        final Button tv_four = keyboardView.findViewById(R.id.four);
        final Button tv_five = keyboardView.findViewById(R.id.five);
        final Button tv_six = keyboardView.findViewById(R.id.six);
        final Button tv_seven = keyboardView.findViewById(R.id.seven);
        final Button tv_eight = keyboardView.findViewById(R.id.eight);
        final Button tv_nine = keyboardView.findViewById(R.id.nine);
        final Button tv_zero = keyboardView.findViewById(R.id.zero);
        final Button tv_confirm = keyboardView.findViewById(R.id.confirm);
        final Button tv_cancel = keyboardView.findViewById(R.id.cancel);
        final Button tv_delete = keyboardView.findViewById(R.id.delete);
        tv_zero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_zero);
            }
        });

        tv_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_one);
            }
        });

        tv_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_two);
            }
        });

        tv_three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_three);
            }
        });

        tv_four.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_four);
            }
        });

        tv_five.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_five);
            }
        });

        tv_six.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_six);
            }
        });

        tv_seven.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_seven);
            }
        });

        tv_eight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_eight);
            }
        });

        tv_nine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAppendData(tv_nine);
            }
        });

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Exit();
                finish();
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String sn = OtherUtil.getInstance().getAppSerial(OtherUtil.getMainContext());
                new FetchKDLjmTask(kd3_ljm.getText().toString().trim(),sn).execute();
            }
        });

        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String editextStr = kd3_ljm.getText().toString().trim();
                if (editextStr.length() > 0) {
                    kd3_ljm.setText(editextStr.substring(0, editextStr.length() - 1));
                }
                cursorLast(kd3_ljm);
            }
        });


        iv_delete = (ImageView) findViewById(R.id.iv_delete);
        iv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                kd3_ljm.setText("");
            }
        });

        mVisible = true;getSupportActionBar().hide();

        hideSoftInputMethod(kd3_ljm);
        //kd3_ljm.setFocusableInTouchMode(false);
        kd3_ljm.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().trim().length() > 0) {
                    kd3_ljm.setHeight(OtherUtil.dp2px(200));
                    kd3_ljm.setBackgroundResource(R.mipmap.editext_background_active);
                    iv_delete.setVisibility(View.VISIBLE);
                } else {
                    kd3_ljm.setHeight(OtherUtil.dp2px(120));
                    kd3_ljm.setBackgroundResource(R.drawable.bg_blue_button_stroke);
                    iv_delete.setVisibility(View.GONE);
                }

                if (editable.toString().trim().length() == 6) {
                    String sn = OtherUtil.getInstance().getAppSerial(OtherUtil.getMainContext());
                    new FetchKDLjmTask(editable.toString().trim(),sn).execute();
                }
            }
        });

        TextView kd3_qx = (TextView) findViewById(R.id.tv_back);
        kd3_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(4005, intent);
                    Exit();
                    finish();

                }
            }
        });

        TextView tv_version = findViewById(R.id.tv_version);
        TextView tv_waiter = findViewById(R.id.tv_waiter);
        try {
            tv_version.setText("v" + OtherUtil.getVersion(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = sharedPreferences.getString("CabinetType_phone","");
        tv_waiter.setText("客服电话:" + phone);

        ImageView kd3_list = (ImageView) findViewById(R.id.kd3_list);
        kd3_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(4007, intent);
                    Exit();
                    finish();

                }
            }
        });
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                //djs.setText(String.valueOf(OtherUtil.jjcount));
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(4005, intent);
                    Exit();
                    finish();
                }

            }
        },0,1000);
    }

    private void inputAppendData(Button tv_one) {
        String a = kd3_ljm.getText().toString().trim();
        String b = tv_one.getText().toString().trim();
        kd3_ljm.setText(a + b);
        //光标显示到最后
        cursorLast(kd3_ljm);
    }

    private void cursorLast(EditText idEdit) {
        Editable etext = idEdit.getText();
        Selection.setSelection(etext, etext.length());
    }

    private void hideSoftInputMethod(EditText ed) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        int currentVersion = android.os.Build.VERSION.SDK_INT;
        String methodName = null;
        if (currentVersion >= 16) {
            // 4.2
            methodName = "setShowSoftInputOnFocus";
        } else if (currentVersion >= 14) {
            // 4.0
            methodName = "setSoftInputShownOnFocus";
        }

        if (methodName == null) {
            ed.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            try {
                setShowSoftInputOnFocus = cls.getMethod(methodName, boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(ed, false);
            } catch (NoSuchMethodException e) {
                ed.setInputType(InputType.TYPE_NULL);
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    }

    private void Exit(){
        EventBus.getDefault().unregister(this);
    }
    
    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;


    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mVisible = true;


    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10402:
                handleKDLjmTask(message.obj);
                break;
            case 10403:
                Toast.makeText(Kd3Activity.this, "揽件码错误", Toast.LENGTH_SHORT).show();
                break;
            case 20000:
                handleDJS();
                break;
            case 20001:
                handleDJS2();
                break;
        }
    }

    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }
    private void handleDJS2(){
        dialog_djs.setText(jjcount2 + "");
    }

    private void handleKDLjmTask(Object obj)
    {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

                String id = result.getJSONObject("data").getString("id");
                String name = result.getJSONObject("data").getString("name");
                String phone = result.getJSONObject("data").getString("phone");
                String toname = result.getJSONObject("data").getString("toname");
                String cardid = result.getJSONObject("data").getString("cardid");
                String exp_type = result.getJSONObject("data").getString("exp_type");
                String packageid = result.getJSONObject("data").getString("packageid");
                String gridnum = result.getJSONObject("data").getString("gridnum");
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("kd_lj_id",id);
                editor.putString("kd_lj_name",name);
                editor.putString("kd_lj_phone",phone);
                editor.putString("kd_lj_toname",toname);
                editor.putString("kd_lj_cardid",cardid);
                editor.putString("kd_lj_exp_type",exp_type);
                editor.putString("kd_lj_packageid",packageid);
                editor.putString("kd_gridnum",gridnum);
                editor.apply();


                Intent intent = new Intent();
                //intent.putExtra("sn", resultString);
                intent.putExtra("kd_lj_name", name);
                intent.putExtra("kd_lj_cardid", cardid);
                LogUtil.getInstance().info(OtherUtil.getCurrentTime()+"Kd3Activity揽件码揽件:"+ "name " + name + "cardid " + cardid );
                setResult(4006, intent);
                Exit();
                finish();
            }else{
                /*View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 2000);*/

                showFailDialog();

            }

        }catch(Exception e){
            View cv = getWindow().getDecorView();
            AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
            adbuilder.setTitle("网络异常");
            adbuilder.setMessage("2秒后自动关闭！");
            adbuilder.setCancelable(true);
            final AlertDialog dlg = adbuilder.create();
            dlg.show();
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    dlg.dismiss();
                    t.cancel();
                }
            }, 2000);
        }
    }

    private void showFailDialog() {
        View view = View.inflate(this, R.layout.dialog_fail, null);
        initDialogView(view);
        commitDialog = new CustomDialog(this, OtherUtil.dp2px(500), OtherUtil.dp2px(560),
                view, R.style.CustomDialog);
        commitDialog.show();
    }

    private void initDialogView(View view) {
        jjcount2 = 5;
        dialog_djs = view.findViewById(R.id.tv_djs);
        btn_confirm = view.findViewById(R.id.btn_confirm);
        tv_hint = view.findViewById(R.id.tv_hint);
        dialog_djs.setText(jjcount2 + "");
        tv_hint.setText("揽件码错误");

        countTimer2=new Timer();
        countTimer2.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount2--;
                Message message = new Message();
                message.what=20001;
                EventBus.getDefault().post(message);
                if(jjcount2 < 1){
                    closeDialog();
                    countTimer2.cancel();
                }
            }
        },0,1000);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });
    }

    private void closeDialog() {
        if (commitDialog != null && commitDialog.isShowing()) {
            commitDialog.dismiss();
        }
    }
}
